package com.zhigongtech.core.web.config;

import java.util.concurrent.Executor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import lombok.extern.slf4j.Slf4j;

@EnableAsync
@Configuration
@ConditionalOnProperty(name="spring.async.maxPoolSize")
@Slf4j
public class AsyncConfiguration {

	@Value("${spring.async.maxPoolSize:10}")
	private int maxPoolSize;
	
	@Bean("taskExecutor")
    public Executor taskExecutor(){
		log.info("start Async taskExecutor init  .....................");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        taskExecutor.setAwaitTerminationSeconds(60);//设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        taskExecutor.setCorePoolSize(1);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(Integer.MAX_VALUE);//缓冲执行任务的队列
        taskExecutor.setKeepAliveSeconds(60);//当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setThreadNamePrefix("kanjia-websocket-thread-");
        return taskExecutor;
    }
}
